const route = require('koa-router')();
const User = require('../../model/user/user.js')
const jwt = require('jsonwebtoken')

route.post('/login',async(ctx,next)=>{
    let requestData = ctx.request.body
    if(!requestData.mobile){
        ctx.body = {
            code:400,
            msg:'手机号码不能为空'
        }
    }else if(!requestData.password){
        ctx.body = {
            code:400,
            msg:'密码不能为空'
        }
    }else{//开始匹配
        let findinfo = (await User.find({mobile:requestData.mobile}))[0]//根据手机号码找到记录
        if(!findinfo){//如果没有匹配到手机号码
            ctx.body = {
                code:400,
                msg:'用户不存在'
            }
        }else{//找到一条记录，验证密码
            if(requestData.password == findinfo.password){
                let payload = {
                    userid:findinfo.user_id
                }
                let sign = 'book';
                let options = {
                    expiresIn:'360 days'
                }
                let token = jwt.sign(payload,sign,options)
                ctx.body = {
                    code:200,
                    msg:'ok',
                    data:{
                        token,
                        user_id:findinfo.user_id
                    }
                }
            }else{
                ctx.body = {
                    code:400,
                    msg:'密码错误'
                }
            }
            
        }
    }
})

module.exports = route